package repository

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/jiebaiyou/formflow/model/questions"
	"gitee.com/jiebaiyou/formflow/pkg/ptr"
	"gitee.com/jiebaiyou/formflow/pkg/storage/redis"
	"gitee.com/jiebaiyou/formflow/pkg/storage/sqlite"
)

// questionRepository 实现了题目仓储接口, 负责题目数据的持久化
type questionRepository struct {
	db    sqlite.DB
	cache redis.Database
}

// NewQuestionRepository 创建题目仓储实例
func NewQuestionRepository(db sqlite.DB, cache redis.Database) questions.QuestionRepository {
	return &questionRepository{
		db:    db,
		cache: cache,
	}
}

// GetQuestionTemplates 获取题目模板
func (r *questionRepository) GetQuestionTemplates(ctx context.Context, types []questions.QuestionType) (questions.QuestionTemplate, error) {
	// 初始化空模板 - 不预填充任何字段，依靠omitempty标签处理
	template := questions.QuestionTemplate{}

	// 如果未指定类型，返回所有题型的默认模板
	if len(types) == 0 {
		scq := createSingleChoiceTemplate()
		mcq := createMultipleChoiceTemplate()
		fbq := createFillBlankTemplate()
		tfq := createTrueFalseTemplate()
		saq := createShortAnswerTemplate()
		rq := createRatingTemplate()

		template = questions.QuestionTemplate{
			SingleChoiceQuestion:   &scq,
			MultipleChoiceQuestion: &mcq,
			FillBlankQuestion:      &fbq,
			TrueFalseQuestion:      &tfq,
			ShortAnswerQuestion:    &saq,
			RatingQuestion:         &rq,
		}
		return template, nil
	}

	// 处理传入的每个题型
	for _, qType := range types {
		switch qType {
		case questions.SingleChoice:
			scq := createSingleChoiceTemplate()
			template.SingleChoiceQuestion = &scq
		case questions.MultipleChoice:
			mcq := createMultipleChoiceTemplate()
			template.MultipleChoiceQuestion = &mcq
		case questions.FillBlank:
			fbq := createFillBlankTemplate()
			template.FillBlankQuestion = &fbq
		case questions.TrueFalse:
			tfq := createTrueFalseTemplate()
			template.TrueFalseQuestion = &tfq
		case questions.ShortAnswer:
			saq := createShortAnswerTemplate()
			template.ShortAnswerQuestion = &saq
		case questions.Rating:
			rq := createRatingTemplate()
			template.RatingQuestion = &rq
		}
	}

	return template, nil
}

// 创建单选题模板
func createSingleChoiceTemplate() questions.SingleChoiceQuestion {
	return questions.SingleChoiceQuestion{
		BaseQuestion: questions.BaseQuestion{
			ID:          "template-single-choice",
			Type:        questions.SingleChoice,
			Title:       "单选题模板",
			Description: "这是一个单选题模板",
			Required:    true,
			Order:       1,
			Enabled:     true,
			Tags:        []string{"数学", "简单"},
			Category:    "单选题",
		},
		Settings: &questions.SingleChoiceSettings{
			Options: []*questions.SingleChoiceOption{
				{ID: ptr.Int(1), Text: "选项一", Order: 1},
				{ID: ptr.Int(2), Text: "选项二", Order: 2},
				{ID: ptr.Int(3), Text: "选项三", Order: 3},
				{ID: ptr.Int(4), Text: "选项四", Order: 4},
			},
			CorrectOption:  ptr.Int(1),
			DisplayType:    "radio",
			Randomize:      false,
			HasOtherOption: false,
		},
	}
}

// 创建多选题模板
func createMultipleChoiceTemplate() questions.MultipleChoiceQuestion {
	return questions.MultipleChoiceQuestion{
		BaseQuestion: questions.BaseQuestion{
			ID:          "template-multiple-choice",
			Type:        questions.MultipleChoice,
			Title:       "多选题模板",
			Description: "这是一个多选题模板",
			Required:    true,
			Order:       1,
			Enabled:     true,
			Tags:        []string{"语文", "简单"},
			Category:    "多选题",
		},
		Settings: &questions.MultipleChoiceSettings{
			Options: []*questions.MultipleChoiceOption{
				{ID: ptr.Int(1), Text: "选项一", Order: 1},
				{ID: ptr.Int(2), Text: "选项二", Order: 2},
				{ID: ptr.Int(3), Text: "选项三", Order: 3},
				{ID: ptr.Int(4), Text: "选项四", Order: 4},
			},
			CorrectOptions: []int{2, 3},
			DisplayType:    "checkbox",
			Randomize:      false,
			HasOtherOption: false,
		},
	}
}

// 创建填空题模板
func createFillBlankTemplate() questions.FillBlankQuestion {
	return questions.FillBlankQuestion{
		BaseQuestion: questions.BaseQuestion{
			ID:          "template-fill-blank",
			Type:        questions.FillBlank,
			Title:       "填空题模板",
			Description: "这是一个填空题模板",
			Required:    true,
			Order:       1,
			Enabled:     true,
			Tags:        []string{"英语", "简单"},
			Category:    "填空题",
		},
		Settings: &questions.TextInputSettings{
			Blanks: []*questions.BlankField{
				{ID: "blank1", Order: 1, InputType: "text", Placeholder: "请输入答案", MinLength: nil, MaxLength: nil, DefaultValue: "", Width: 0},
			},
			ContentTemplate: "请输入{{1}}",
			CaseSensitive:   false,
			PartialScoring:  false,
			ScoreStrategy:   "all_or_nothing",
		},
	}
}

// 创建判断题模板
func createTrueFalseTemplate() questions.TrueFalseQuestion {
	return questions.TrueFalseQuestion{
		BaseQuestion: questions.BaseQuestion{
			ID:          "template-true-false",
			Type:        questions.TrueFalse,
			Title:       "判断题模板",
			Description: "这是一个判断题模板",
			Required:    true,
			Order:       1,
			Enabled:     true,
			Tags:        []string{"数学", "简单"},
			Category:    "判断题",
		},
		Settings: &questions.TrueFalseSetting{
			Statement:     "地球是太阳系中的第三颗行星。",
			TrueLabel:     "正确",
			FalseLabel:    "错误",
			CorrectAnswer: true,
			Explanation:   "地球确实是太阳系中距离太阳由近到远的第三颗行星。",
			Required:      true,
			LabelAlign:    "left",
		},
	}
}

// 创建简答题模板
func createShortAnswerTemplate() questions.ShortAnswerQuestion {
	return questions.ShortAnswerQuestion{
		BaseQuestion: questions.BaseQuestion{
			ID:          "template-short-answer",
			Type:        questions.ShortAnswer,
			Title:       "简答题模板",
			Description: "这是一个简答题模板",
			Required:    true,
			Order:       1,
			Enabled:     true,
			Tags:        []string{"数学", "简单"},
			Category:    "简答题",
		},
		Settings: &questions.ShortAnswerSettings{
			Placeholder:  "请输入您的回答",
			Rows:         5,
			MinLength:    nil,
			MaxLength:    nil,
			DefaultValue: "",
			RichText:     false,
		},
	}
}

// 创建评分题模板
func createRatingTemplate() questions.RatingQuestion {
	return questions.RatingQuestion{
		BaseQuestion: questions.BaseQuestion{
			ID:          "template-rating",
			Type:        questions.Rating,
			Title:       "评分题模板",
			Description: "这是一个评分题模板",
			Required:    true,
			Order:       1,
			Enabled:     true,
			Tags:        []string{"数学", "简单"},
			Category:    "评分题",
		},
		Settings: &questions.RatingSettings{
			RatingType: "star",
			MinRating:  ptr.Int(1),
			MaxRating:  ptr.Int(5),
			Step:       1,
			Labels:     []string{"很差", "较差", "一般", "较好", "很好"},
			Direction:  "horizontal",
		},
	}
}

// CreateQuestion 创建题目
func (r *questionRepository) CreateQuestion(ctx context.Context, template *questions.QuestionTemplate) error {
	// 根据题型, 将题目模板写入redis
	if template.SingleChoiceQuestion != nil {
		jsonData, _ := json.Marshal(template.SingleChoiceQuestion)
		res, err := r.cache.JSONSet(ctx, "hs-123143-com:system:question:template:singleChoice", "$", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository JSONSet ->", res)

		result, err := r.cache.HSet(ctx, "hs-123143-com:system:question:template", "singleChoice", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HSet ->", result)

		getres, err := r.cache.HGet(ctx, "hs-123143-com:system:question:template", "singleChoice")
		if err != nil {
			return err
		}
		fmt.Printf("---> repository JSONSet %v, HSet %v, HGet %v\n", res, result, getres)
	}

	if template.MultipleChoiceQuestion != nil {
		jsonData, _ := json.Marshal(template.MultipleChoiceQuestion)
		res, err := r.cache.JSONSet(ctx, "hs-123143-com:system:question:template:multipleChoice", "$", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository JSONSet ->", res)

		result, err := r.cache.HSet(ctx, "hs-123143-com:system:question:template", "multipleChoice", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HSet ->", result)

		getres, err := r.cache.HGet(ctx, "hs-123143-com:system:question:template", "multipleChoice")
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HGet ->", res)
		fmt.Printf("---> repository JSONSet %v, HSet %v, HGet %v\n", res, result, getres)
	}

	if template.TrueFalseQuestion != nil {
		jsonData, _ := json.Marshal(template.TrueFalseQuestion)
		res, err := r.cache.JSONSet(ctx, "hs-123143-com:system:question:template:trueFalse", "$", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository JSONSet ->", res)

		result, err := r.cache.HSet(ctx, "hs-123143-com:system:question:template", "trueFalse", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HSet ->", result)

		getres, err := r.cache.HGet(ctx, "hs-123143-com:system:question:template", "trueFalse")
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HGet ->", res)
		fmt.Printf("---> repository JSONSet %v, HSet %v, HGet %v\n", res, result, getres)
	}

	if template.ShortAnswerQuestion != nil {
		jsonData, _ := json.Marshal(template.ShortAnswerQuestion)
		res, err := r.cache.JSONSet(ctx, "hs-123143-com:system:question:template:shortAnswer", "$", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository JSONSet ->", res)

		result, err := r.cache.HSet(ctx, "hs-123143-com:system:question:template", "shortAnswer", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HSet ->", result)

		getres, err := r.cache.HGet(ctx, "hs-123143-com:system:question:template", "shortAnswer")
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HGet ->", res)
		fmt.Printf("---> repository JSONSet %v, HSet %v, HGet %v\n", res, result, getres)
	}

	if template.RatingQuestion != nil {
		jsonData, _ := json.Marshal(template.RatingQuestion)
		res, err := r.cache.JSONSet(ctx, "hs-123143-com:system:question:template:rating", "$", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository JSONSet ->", res)

		result, err := r.cache.HSet(ctx, "hs-123143-com:system:question:template", "rating", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HSet ->", result)

		getres, err := r.cache.HGet(ctx, "hs-123143-com:system:question:template", "rating")
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HGet ->", res)
		fmt.Printf("---> repository JSONSet %v, HSet %v, HGet %v\n", res, result, getres)
	}

	if template.FillBlankQuestion != nil {
		jsonData, _ := json.Marshal(template.FillBlankQuestion)
		res, err := r.cache.JSONSet(ctx, "hs-123143-com:system:question:template:fillBlank", "$", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository JSONSet ->", res)

		result, err := r.cache.HSet(ctx, "hs-123143-com:system:question:template", "fillBlank", jsonData)
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HSet ->", result)

		getres, err := r.cache.HGet(ctx, "hs-123143-com:system:question:template", "fillBlank")
		if err != nil {
			return err
		}
		// fmt.Println("-- repository HGet ->", res)
		fmt.Printf("---> repository JSONSet %v, HSet %v, HGet %v\n", res, result, getres)
	}
	return nil
}

// UpdateQuestion 更新题目
func (r *questionRepository) UpdateQuestion(ctx context.Context, questionID string) error {
	return nil
}

// DeleteQuestion 删除题目
func (r *questionRepository) DeleteQuestion(ctx context.Context, questionID string) error {
	return nil
}

// GetQuestionByID 获取题目
func (r *questionRepository) GetQuestionByID(ctx context.Context, questionID string) (any, error) {
	return nil, nil
}

// ListQuestions 获取题目列表
func (r *questionRepository) ListQuestions(ctx context.Context) ([]any, error) {
	return nil, nil
}
